package com.osce.web.controller.system;

import com.osce.common.constant.Constants;
import com.osce.common.core.entity.AjaxResult;
import com.osce.common.core.entity.entity.SysMenu;
import com.osce.common.core.entity.entity.SysUser;
import com.osce.common.core.entity.model.LoginBody;
import com.osce.common.utils.SecurityUtils;
import com.osce.framework.web.service.SysLoginService;
import com.osce.framework.web.service.SysPermissionService;
import com.osce.interfaces.system.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;


    @PostMapping("/login-face/base64")
    public AjaxResult test(@RequestBody List<String> base64) {
        return AjaxResult.success().put(Constants.TOKEN, loginService.loginFace(base64.get(0)));
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        return AjaxResult.success().put(Constants.TOKEN, loginService.login(loginBody));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return AjaxResult.success().put("user", user).
                put("roles", permissionService.getRolePermission(user)). // 角色集合
                        put("roleIds", permissionService.getRoleIds(user)).// 角色ID集合
                        put("permissions", permissionService.getMenuPermission(user));// 权限集合
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
